package com.wbao.dianniu.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.data.Martis;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.data.WorkExperienceData;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.ui.AmDetailActivity;
import com.wbao.dianniu.ui.HeadInfoActivity;
import com.wbao.dianniu.ui.QaDetailActivity;
import com.wbao.dianniu.viewpager.MyViewPager;

public class Utils {
	
//	static final String TAG = "Utils";
	public static final String DIRECTORY;
	public static final ExecutorService SERVICE;
	private static final String WORKSPLIT = "\\|.\\|\\|\\|.\\|";
	private static final String DATASPLIT = ".\\|\\|\\|.";

	static {
		SERVICE = Executors.newCachedThreadPool();
		String DCIM = Environment.getExternalStoragePublicDirectory(
				Environment.DIRECTORY_DCIM).toString();
		DIRECTORY = DCIM + "/Camera";
	}

	/**
	 * 频繁获取同文件，同时间的截图，可以尝试Memory cache bitmap，提高速度，
	 * 
	 * @param filePath
	 * @param fd
	 * @param timeUs
	 * @return
	 */
	public static Bitmap createVideoThumbnail(String filePath,
			FileDescriptor fd, long timeUs) {
		Bitmap bitmap = null;
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		try {
			if (filePath != null) {
				retriever.setDataSource(filePath);
			} else {
				retriever.setDataSource(fd);
			}
			bitmap = retriever.getFrameAtTime(timeUs);
		} catch (Throwable throwable) {
			// Assume this is a corrupt video file
		} finally {
			try {
				retriever.release();
			} catch (RuntimeException ex) {
			}
		}
		return bitmap;
	}
	

	public static Martis getMetrics(WindowManager manager) {
		DisplayMetrics metric = new DisplayMetrics();
		manager.getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度（像素）
		int height = metric.heightPixels; // 屏幕高度（像素）
//		float density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
//		int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240）
		Martis martis = new Martis();
		martis.setWidth(width);
		martis.setHeight(height);
		return martis;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 获取网落图片资源
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getHttpBitmap(String url) {
		URL myFileURL;
		Bitmap bitmap = null;
		try {
			myFileURL = new URL(url);
			// 获得连接
			HttpURLConnection conn = (HttpURLConnection) myFileURL
					.openConnection();
			// 设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
			conn.setConnectTimeout(6000);
			// 连接设置获得数据流
			conn.setDoInput(true);
			// 不使用缓存
			conn.setUseCaches(false);
			// 这句可有可无，没有影响
			// conn.connect();
			// 得到数据流
			InputStream is = conn.getInputStream();
			// 解析得到图片
			bitmap = BitmapFactory.decodeStream(is);
			// 关闭数据流
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	public boolean isMobile(String mobile) {
		return mobile.matches("^(13|15|18|14|17)\\d{9}$");
	}

	public  static String Md5(String str) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	public static String inputStream2String(InputStream is, String charset) {
        ByteArrayOutputStream baos = null;  
        try {  
            baos = new ByteArrayOutputStream();  
            int i = -1;  
            while ((i = is.read()) != -1) {  
                baos.write(i);  
            }  
            return baos.toString(charset);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (null != baos) {  
                try {  
                    baos.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                baos = null;  
            }  
        }  
        return null;  
    } 
	
	public static int getMaxCounts(String str,Context context){
		int position = -1;
		String[] section_arrays = context.getResources().getStringArray(R.array.activity_peoples_array);
		for (int i = 0; i < section_arrays.length; i++) {
			if(section_arrays[i].equals(str)){
			position = i;
			break;
			}
		}
		if(-1 != position){
			int[] maxCounts = context.getResources().getIntArray(R.array.activity_peoples_ID);
			return maxCounts[position];
		}else{
			return position;
		}
	}
	
	
	/**
	 * 为字体改变颜色
	 * 
	 * @param textView
	 * @param content
	 */
	public static void TextColorShow(TextView textView, String content){
		SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());  
		//ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色  
		ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED); 
		int start = textView.getText().toString().trim().indexOf(content);
		builder.setSpan(redSpan, start, start + content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
		textView.setText(builder);
	}
	
	
	public static String getFormatDate(String date){
		if(date.length() >= 10){
			return date.substring(0, 10);
		}else{
			return "";
		}
	}
	
	public static void saveLoginData(LoginResponse objdata){
		GlobalContext.token = objdata.getToken();
		GlobalContext.cdnToken = objdata.getCdnToken();
		GlobalContext.environment = objdata.getEnvironmentName();
		GlobalContext.accountId = objdata.getAccountInfo().getId();
		GlobalContext.mobile = objdata.getAccountInfo().getMobile();
		/**	保存隐私设置数据可见	*/
		GlobalContext.dataprivacy = objdata.getAccountInfo().getDataPrivacy();
		/**	保存隐私设置是否可加好友	*/
		GlobalContext.beFriend = objdata.getAccountInfo().getBeFriend();
		/**	暂时屏蔽掉下载地址同步  	*/
//		GlobalContext.cdndownUrl = objdata.getConfig().getCdnDownUrl();
//		GlobalContext.cdnUpUrl = objdata.getConfig().getCdnUpUrl();
		
		GlobalContext._ID = objdata.getAccountInfo().getId();
		GlobalContext.headPic = objdata.getAccountInfo().getHeadPic();
		GlobalContext.niceName = objdata.getAccountInfo().getRealName();
		GlobalContext.signate = objdata.getAccountInfo().getDescribe();
		GlobalContext.label = objdata.getAccountInfo().getLabel();
		GlobalContext.resumeStatus = objdata.getAccountInfo().getResumeStatus();
		GlobalContext.isPerfectResume = objdata.getAccountInfo().getIsPerfectResume();
		GlobalContext.isPerfectData = objdata.getAccountInfo().isPerfectData();
		GlobalContext.isIndustryAuthority = objdata.getAccountInfo().isIndustryAuthority();
		
	}
	
	/**
	 * 强制隐藏键盘
	 * 
	 * @param context
	 * @param view
	 */
	public static void hideSoftInput(Context context, View view){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏键盘
	}
	
	/**
	 * 格式化时间（面试时间、入职时间、离职时间）
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
		String str = format.format(date);
		return str;
	}
	
	/**
	 * 
	 * @param startDate  yyyy-MM-dd HH:mm:ss 格式时间
	 * @return  true: 活动已结束，false：活动未开始
	 */
	public static boolean IsActivityStart(String startDate){
		boolean ret = false;
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			ret = date.after(format.parse(startDate));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	/**
	 * 
	 * @param startDate  yyyy-MM-dd HH:mm:ss 格式时间
	 * @return  true: 结束时间大于起始时间，false：结束时间小于起始时间
	 */
	public static boolean IsEndAfterStart(String startDate,String endDate){
		boolean ret = false;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date sDate =format.parse(startDate + " 00:00:00");
			Date eDate = format.parse(endDate + " 00:00:00");
			ret = eDate.after(sDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	public static List<WorkExperienceData> parseWorkData(String data){
		List<WorkExperienceData> list = new ArrayList<WorkExperienceData>();
		String[] str = data.split(WORKSPLIT);
		for (int i = 0; i < str.length; i++) {
			String[] jobs = str[i].split(DATASPLIT);
			if(jobs.length == 5){
				WorkExperienceData jobWorkData = new WorkExperienceData();
//				jobWorkData.setJobId(GlobalContext.accountId);
				jobWorkData.setId(Integer.valueOf(jobs[0]));
				jobWorkData.setStartDate(jobs[1]);
				jobWorkData.setEndDate(jobs[2]);
				jobWorkData.setPost(jobs[3]);
				jobWorkData.setContent(jobs[4]);
				list.add(jobWorkData);
			}
		}
		return list;
	}
	
	public static String WorkListDataToString(List<WorkExperienceData> list){
		String str = "";
		if(list.size() == 0){
			return str;
		}
		str =  list.get(0).getId() + ".|||." + list.get(0).getStartDate()+".|||." + list.get(0).getEndDate()+".|||."
				+list.get(0).getPost()+".|||." + list.get(0).getContent();
		for (int i = 1; i < list.size(); i++) {
			str= str + "|.|||.|" +  list.get(i).getId() + ".|||." + list.get(i).getStartDate()+".|||." + list.get(i).getEndDate()+".|||."
					+list.get(i).getPost()+".|||." + list.get(i).getContent() ;
		}
		return str;
	}
	
	public static void intoHeadInfoActivity(Integer accountId,Context context){
//		if( accountId == GlobalContext.accountId){
//			Intent headIntent = new Intent();
//			headIntent.setClass(context, PerfectInfoActivity.class);
//			context.startActivity(headIntent);
//		}else{
			Intent headIntent = new Intent();
			headIntent.putExtra(HeadInfoActivity.INTENT_FRIENDID, accountId);
			headIntent.setClass(context, HeadInfoActivity.class);
			context.startActivity(headIntent);
//		}
	}
	
	@TargetApi(19)
	public static void setTranslucentStatus(Activity context , boolean on) {
		Window win = context.getWindow();
		WindowManager.LayoutParams winParams = win.getAttributes();
		final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
		if (on) {
			winParams.flags |= bits;
		} else {
			winParams.flags &= ~bits;
		}
		win.setAttributes(winParams);
	}
	
	public static void intoQaDetailActivity(Context context, QaResponse resp){
		Intent contentIntent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putString(GlobalContext.BUNDLE_HEADPIC, resp.headPic);
		bundle.putString(GlobalContext.BUNDLE_REALNAME, resp.realName);
		bundle.putString(GlobalContext.BUNDLE_LABEL, resp.label);
		bundle.putInt(GlobalContext.BUNDLE_ISGOOD, resp.isGood);
		bundle.putString(GlobalContext.BUNDLE_CONTENT, resp.content);
		bundle.putInt(GlobalContext.BUNDLE_VISITORCOUNT, resp.visitorCount);
		bundle.putInt(GlobalContext.BUNDLE_FORWARDCOUNT, resp.forwardCount);
		bundle.putInt(GlobalContext.BUNDLE_GOODCOUNT, resp.goodCount);
		bundle.putInt(GlobalContext.BUNDLE_ANSWERCOUNT, resp.answerCount);
		bundle.putInt(GlobalContext.BUNDLE_ACCOUNTID, resp.accountId);
		bundle.putInt(GlobalContext.BUNDLE_QUESTID, resp.id);
		bundle.putString(GlobalContext.BUNDLE_QUESTIMGS, resp.questImgs);
		contentIntent.putExtra(GlobalContext.QA_DATA_BUNDLE, bundle);
		contentIntent.setClass(context, QaDetailActivity.class);
		context.startActivity(contentIntent);
	}
	
	public static void intoAmDetailActivity(Context context, QaResponse resp){
		Intent contentIntent = new Intent();
		Bundle bundle = new Bundle();
		if(0 == resp.showAliasName){
			bundle.putString(GlobalContext.BUNDLE_REALNAME, "");
		}else{
			bundle.putString(GlobalContext.BUNDLE_REALNAME, resp.realName);
		}
		bundle.putInt(GlobalContext.BUNDLE_ISGOOD, resp.isGood);
		bundle.putString(GlobalContext.BUNDLE_CONTENT, resp.content);
		bundle.putInt(GlobalContext.BUNDLE_VISITORCOUNT, resp.visitorCount);
		bundle.putInt(GlobalContext.BUNDLE_FORWARDCOUNT, resp.forwardCount);
		bundle.putInt(GlobalContext.BUNDLE_GOODCOUNT, resp.goodCount);
		bundle.putInt(GlobalContext.BUNDLE_ANSWERCOUNT, resp.answerCount);
		bundle.putInt(GlobalContext.BUNDLE_ACCOUNTID, 	resp.accountId);
		bundle.putInt(GlobalContext.BUNDLE_QUESTID, resp.id);
		bundle.putString(GlobalContext.BUNDLE_QUESTIMGS, resp.questImgs);
		contentIntent.putExtra(GlobalContext.AM_DATA_BUNDLE, bundle);
		contentIntent.setClass(context, AmDetailActivity.class);
		context.startActivity(contentIntent);
	}
	
	public static void imageBrower(Context context, int position, ArrayList<String> imageUrls){
		 Intent intent = new Intent(context, MyViewPager.class);
	        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
	        intent.putExtra(MyViewPager.EXTRA_IMAGE_URLS, imageUrls);
	        intent.putExtra(MyViewPager.EXTRA_IMAGE_INDEX, position);
	        context.startActivity(intent);
	        ((Activity)context).overridePendingTransition(R.anim.zoom_enter, 0);
	}
	
	/**
	 * 显示浏览，评论，点赞数
	 * 
	 * @param goodCount
	 * @param praiseTV
	 */
	public static void showPriseCounts(int goodCount, TextView praiseTV) {
		if (goodCount > 10000) {
			float conts = (float) Math.ceil(goodCount / 1000.0);
			DecimalFormat fnum = new DecimalFormat("##0.0");
			if (conts % 10 > 0) {
				praiseTV.setText(fnum.format(conts / 10) + "万");
			} else {
				praiseTV.setText((int) conts / 10 + "万");
			}
		} else {
			praiseTV.setText(goodCount + "");
		}
	}
	
}
